//
//  Station.m
//  TrainTrack
//
//  Created by Philip Bruce on 5/10/08.
//  Copyright 2008 Den Falske Zebra. All rights reserved.
//

#import "Station.h"

@implementation Station

@synthesize name, location, distanceFromCurrentLocation, distanceFromCurrentLocationText;

static sqlite3 *database;
static NSArray *allStations;

// return the name of the station
-(NSString *)description {
	return self.name;
}

// find all stations within a limit from some location
+(NSArray *)findAllSortedByDistanceToLocation:(CLLocation *)loc {
	NSMutableArray *stations = [NSMutableArray array];
	
	for(Station *station in allStations) {
		CLLocationDistance distance = [station.location getDistanceFrom:loc];
		station.distanceFromCurrentLocation = distance/1000;
		station.distanceFromCurrentLocationText = [NSString stringWithFormat:@"%.1f km", distance/1000];
		[stations addObject:station];
	}
	
	// order stations by distance from current location
	[stations sortUsingSelector:@selector(compareDistances:)];
	
	return stations;
}

// set the database to search for stations
+(void)setDatabase:(sqlite3 *)db {
	database = db;
}

// find all stations and return them as station objects in an array
+(void)findAll {
	sqlite3_stmt *refresh_statement = nil;
	
	NSMutableArray *stations = [NSMutableArray array];
	
	// Compile the refresh statement, if needed.
	//if (refresh_statement == nil) {
	const char *sql;
	
	NSString *ns_sql = @"SELECT * FROM Stations ORDER BY name";
	sql = [ns_sql UTF8String];
	
	if (sqlite3_prepare_v2(database, sql, -1, &refresh_statement, NULL) != SQLITE_OK) {
		NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
	}
	
	while (sqlite3_step(refresh_statement) == SQLITE_ROW) {
		// Create station object
		Station *station = [[Station alloc] init];
		
		// Set station name
		char *str = (char *)sqlite3_column_text(refresh_statement, 0);
		station.name = (str) ? [NSString stringWithUTF8String:str] : @"";
		
		// set stations location
		CLLocationDegrees latitude = sqlite3_column_double(refresh_statement, 1);	
		CLLocationDegrees longitude = sqlite3_column_double(refresh_statement, 2);
		station.location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
			
		// add station to array
		[stations addObject:station];
	} 
	
	sqlite3_finalize(refresh_statement);
	
	allStations = stations;
	[allStations retain];
}

-(NSComparisonResult)compareDistances:(Station *)station {

	if (self.distanceFromCurrentLocation < station.distanceFromCurrentLocation) {
		return NSOrderedAscending;
	} else if (self.distanceFromCurrentLocation == station.distanceFromCurrentLocation) {
		return NSOrderedSame;
	} else {
		return NSOrderedDescending;
	}
}

@end
